package org.cid54.jshopper.controller;

import org.cid54.jshopper.model.Item;
import org.cid54.jshopper.model.ShopItem;
import org.cid54.jshopper.model.ShoppingList;
import org.cid54.jshopper.service.ShopItemService;
import org.cid54.jshopper.service.ShoppingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author fgo
 */
@Controller
@RequestMapping("shoppingList")
@SessionAttributes({"userName"})
public class ShoppingListItemController {

    @Autowired
    private ShoppingListService shoppingListService;
    @Autowired
    private ShopItemService shopItemService;

    @ModelAttribute("shopItem")
    public ShopItem getShopItem() {
        ShopItem result = new ShopItem();

        result.setItem(new Item());
        result.setShoppingList(new ShoppingList());

        return result;
    }

    @RequestMapping(method = RequestMethod.GET, value = "{shoppingListId}/addItem")
    public ModelAndView doGet(@PathVariable("shoppingListId") long shoppingListId) {

        ModelAndView mav = new ModelAndView("shopItem");

        ShoppingList list = this.shoppingListService.getShoppingListById(shoppingListId);

        mav.addObject("shoppingList", list);

        mav.addObject("items", this.shopItemService.getItems());

        mav.addObject("btnAction", "Save");

        mav.addObject("action", "addItem");

        return mav;

    }

    @RequestMapping(method = RequestMethod.POST, value = "{shoppingListId}/addItem")
    public String doAddPost(ShopItem item, @ModelAttribute("userName") String userName) {

        this.shopItemService.create(item, userName);

        return "redirect:/mvc/shoppingList/" + item.getShoppingList().getId();

    }

    @RequestMapping(method = RequestMethod.POST, value = "{shoppingListId}/{itemId}/toggle")
    public ResponseEntity<String> doToggleBought(@PathVariable("shoppingListId") long shoppingListId, @PathVariable("itemId") long shopItemId){

        this.shopItemService.toggleBoughtStatus(shopItemId);

        return new ResponseEntity<String>(HttpStatus.OK);
    }
}
